<?php

namespace app\admin\controller;

use app\model\customer\WorkPlaceModel;
use app\model\system\SystemAreaModel;
use app\service\statistics\device\CountDrinkService;
use app\service\WorkPlaceService;
use ExAdmin\ui\component\grid\card\Card;
use ExAdmin\ui\component\grid\grid\Actions;
use ExAdmin\ui\component\grid\grid\Filter;
use ExAdmin\ui\component\grid\grid\Grid;
use ExAdmin\ui\component\layout\layout\Layout;
use ExAdmin\ui\component\layout\Row;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use think\facade\Log;
use think\Model;

/**
 * 数据报表控制器
 */
class DataGridController extends AdminBaseController
{

    /**
     * @inheritDoc
     */
    protected function modelSet(): Model
    {
        return new WorkPlaceModel();
    }

    /**
     * 打饮统计
     * @return Grid
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function drink_statistics(): Grid
    {
        $callFunction = function (Grid $grid) {
            $this->hideGridItems($grid);
            //纯表格
            //$grid->table();
            $grid->fontSize(12);
            $grid->column('province', '省份');
            $grid->column('city', '城市');
            $grid->column('work_place', '职场');
            $grid->column('time_frame', '时间范围');
            $grid->column('total_device', '设备总数');
            $grid->column('count_sale_goods_device', '有销量的设备数');
            $grid->column('total_cups', '打饮总杯量');
            $grid->column('count_drink_sale', '饮品销量')->display(function ($value) {
                $layout = Layout::create();
                $chunkData = array_chunk($value, 2);
                foreach ($chunkData as $lines) {
                    // 每行
                    $layout->row(function (Row $row) use ($lines) {
                        foreach ($lines as $colValue) {
                            $row->column(Card::create($colValue)
                                ->size('small')
                                ->style(['font-size' => '12px']), 12);
                        }
                    });
                }
                return $layout;
            });
            $grid->column('count_material', '物料用量')->display(function ($value) {
                $layout = Layout::create();
                $chunkData = array_chunk($value, 2);
                foreach ($chunkData as $lines) {
                    // 每行
                    $layout->row(function (Row $row) use ($lines) {
                        foreach ($lines as $colValue) {
                            $row->column(Card::create($colValue)
                                ->size('small')->style(['font-size' => '12px']), 12);
                        }
                    });
                }
                return $layout;
            });

            // 搜索过滤
            $grid->expandFilter();
            $grid->filter(function (Filter $filter) {
                $filter->enterOnFilter();
                $filter->eq()->radio('time_dimension', '统计维度')
                    ->button()
                    ->options(
                        [1 => "月度", 2 => "季度", 3 => "半年度", 4 => "年度"]
                    );

                $filter->between()
                    ->dateRange('date_range', '日期范围');

                $filter->eq()->cascader(['province_id', 'city_id', 'district_id'], '地区')
                    ->multiple('area_id')->style(['width' => '200px'])->expandTrigger()
                    ->options($this->getAreaOptions());
                $filter->eq()->select('work_place', '职场')->multiple()
                    ->options($this->getWorkPlace());

            });

            // 隐藏删除
            $grid->actions(function (Actions $action) {
                $action->hideDel();
            });

            // 分页设置
            $grid->pagination()
                //设置分页大小
                ->pageSize(10)
                //指定每页可以显示多少条
                ->pageSizeOptions(['10', '15', '20', '25', '30']);
        };
        return Grid::create($this->getDrinkStatisticsData(), $callFunction);
    }

    /**
     * 商品统计
     * @return Grid
     */
    public function goods_statistics(): Grid
    {
        $callFunction = function (Grid $grid) {
            $this->hideGridItems($grid);

            if (!empty(request()->post())) {
                $grid->column("aaa", "aaaa");
            } else {
                $grid->column("bbb", "bbbb");
            }

            // 搜索过滤
            $grid->expandFilter();
            $grid->filter(function (Filter $filter) {
                $filter->eq()->radio('time_dimension', '统计维度')
                    ->button()
                    ->options(
                        [1 => "月度", 2 => "季度", 3 => "半年度", 4 => "年度"]
                    );
                $filter->between()
                    ->dateRange('audit_date', '日期范围');
                $filter->cascader(['province_id', 'city_id', 'district_id'], '地区')
                    ->multiple()
                    ->options($this->getAreaOptions());
                $filter->eq()->select('work_place', '职场')
                    ->options($this->getWorkPlace());
            });

            // 隐藏删除
            $grid->actions(function (Actions $action) {
                $action->hideDel();
            });
        };
        return Grid::create([], $callFunction);
    }


    private function getDrinkStatistics()
    {
        return [
            array(
                "id" => 1,
                "province" => "北京",
                'city' => '北京',
                'work_place' => '大厦1',
                'time_frame' => '2024-01-01 : 2024-02-01',
                'total_device' => '10',
                'count_sale_goods_device' => '2',
                'total_cups' => '100',
                'count_drink_sale' => [
                    '意式咖啡:10', '美式咖啡:10', '卡布奇诺:20', '拿铁玛奇朵:30', '平白咖啡:30',
                ],
                'count_material' => [
                    '热牛奶:10ML', '牛奶:10ML', '咖啡豆1:500克', '咖啡豆2:500克'
                ],
            ),
        ];
    }


    /**
     * 获取区域列表
     * @return array
     */
    private function getAreaOptions(): array
    {
        $areaSet = Db::table($this->model->getTable())->distinct()->field('province_id,city_id,district_id')->order(['id' => 'desc'])->column('province_id,city_id,district_id');
        $areaIDList = [];
        $optionsList = [];
        if (!empty($areaSet)) {
            foreach ($areaSet as $item) {
                foreach ($item as $area_id) {
                    $areaIDList[] = $area_id;
                }
            }
            $areaIDList = array_unique($areaIDList);
            $modelArea = new SystemAreaModel();
            $optionsList = $modelArea->whereIn('id', $areaIDList)->column('id, name, pid');
        }
        //Log::info("optionsList: ".var_export($optionsList, true));
        return $optionsList;
    }

    /**
     * 获取所有职场
     * @return array|object|null
     */
    private function getWorkPlace()
    {
        $service = new WorkPlaceService();
        return $service->getWorkPlaceIdNameList()->data;
    }

    /**
     * 打饮统计Mock数据
     * @param int $numRecords
     * @return array
     */
    function generateMockData(int $numRecords = 10): array
    {
        $mockData = [];
        $provincesAndCities = [
            ["北京", "北京"],
            ["上海", "上海"],
            ["广东", "深圳"],
            ["浙江", "杭州"],
            ["江苏", "南京"]
        ];

        $workPlaces = ["大厦1", "办公区2", "技术园3", "商业中心4"];
        $drinks = ["意式咖啡", "美式咖啡", "卡布奇诺", "拿铁玛奇朵", "平白咖啡"];
        $materials = ["热牛奶", "牛奶", "咖啡豆1", "咖啡豆2"];

        for ($i = 0; $i < $numRecords; $i++) {
            $provinceCityIndex = array_rand($provincesAndCities);
            $workPlaceIndex = array_rand($workPlaces);
            $timeFrameStart = strtotime("2024-01-01") + rand(0, 30) * 86400;
            $timeFrameEnd = $timeFrameStart + rand(15, 30) * 86400; // 确保结束时间在开始时间之后

            $countDrinkSale = [];
            foreach ($drinks as $drink) {
                $countDrinkSale[] = $drink . ":" . rand(5, 30);
            }

            $countMaterial = [];
            foreach ($materials as $material) {
                $countMaterial[] = $material . ":" . rand(10, 500) . (strpos($material, "牛奶") !== false ? "ML" : "克");
            }

            $mockData[] = [
                "id" => $i + 1,
                "province" => $provincesAndCities[$provinceCityIndex][0],
                'city' => $provincesAndCities[$provinceCityIndex][1],
                'work_place' => $workPlaces[$workPlaceIndex],
                'time_frame' => date('Y-m-d', $timeFrameStart) . " : " . date('Y-m-d', $timeFrameEnd),
                'total_device' => (string)rand(5, 20),
                'count_sale_goods_device' => (string)rand(1, 5),
                'total_cups' => (string)rand(50, 200),
                'count_drink_sale' => $countDrinkSale,
                'count_material' => $countMaterial,
            ];
        }

        return $mockData;
    }

    /**
     * 获取打饮统计数据
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function getDrinkStatisticsData(): array
    {
        $filter = request()->post('ex_admin_filter', []);
        Log::info("ex_admin_filter: " . var_export(request()->post(), true));

        $modelQuery = $this->model->newQuery();
        if (!empty($filter['area_id'])) {
            $whereArea = [];
            foreach ($filter['area_id'] as $area) {
                $map = [];
                if ($area['district_id'] > 0) {
                    $map[] = ['district_id', '=', $area['district_id']];
                }
                if ($area['city_id'] > 0) {
                    $map[] = ['city_id', '=', $area['city_id']];
                }
                if ($area['province_id'] > 0) {
                    $map[] = ['province_id', '=', $area['province_id']];
                }
                $whereArea[] = $map;
            }
            $modelQuery->whereOr($whereArea);
        }

        if (!empty($filter['work_place'])) {
            $modelQuery->whereIn('id', $filter['work_place'], 'or');
        }
        // 职场获取
        $workPlaceList = $modelQuery->with(['device'])->scope(['customer'])
            ->order('id desc')->select()->toArray();
        if (empty($workPlaceList)) return [];
        // 数据列表
        $dataList = [];
        // 时间范围
        $dateRange = '';
        if (!empty($filter['time_dimension'])) {
            // [1 => "月度", 2 => "季度", 3 => "半年度", 4 => "年度"]
            $dateRange = [];
        } elseif (!empty($filter['date_range'])) {
            $dateRange = $filter['date_range'];
        }
        $time_frame = !empty($dateRange) ? implode('-', $dateRange) : date('Y-m-d');
        $countDrinkService = new CountDrinkService();
        foreach ($workPlaceList as $value) {
            $deviceSkuCups = [];
            $deviceTotalCups = [];
            $count_sale_goods_device = 0;
            $count_drink_sale = [];
            // 计算设备但因
            if (!empty($value['device'])) {
                $deviceUUIDList = array_column($value['device'], 'uuid');
                $deviceSkuCups = $countDrinkService->daySkuGroupDrinkName($deviceUUIDList, $dateRange)->data;
                $deviceTotalCups = $countDrinkService->dayTotalGroupDevice($deviceUUIDList, $dateRange)->data;
                $count_sale_goods_device = $value['device_num'] - countValueOccurrences($deviceTotalCups, 0);
            }
            if (!empty($deviceSkuCups)) {
                foreach ($deviceSkuCups as $deviceSkuCup) {
                    $count_drink_sale[] = $deviceSkuCup['drink_sku_name'] . ":" . $deviceSkuCup['sum'];
                }
            }
            $row = [
                "id" => $value['id'],
                "province" => $value['province'],
                'city' => $value['city'],
                'work_place' => $value['name'],
                'time_frame' => $time_frame,
                'total_device' => $value['device_num'],
                'count_sale_goods_device' => $count_sale_goods_device,
                'total_cups' => array_sum($deviceTotalCups),
                'count_drink_sale' => $count_drink_sale,
                'count_material' => [],
            ];

            //Log::info("workPdb:" . var_export($deviceSkuCups, true));

            $dataList[] = $row;
        }
        return $dataList;
    }


}